#!/bin/bash

if [ "$1" == "-d" ]
then
    shift
else
    nodebug=1
fi

showinfo()
{
    tput clear
    echo
    echo "-------------------------------------------------------------------"
    echo "----------- Regression tests for patterns in \`$1' ----------------"
    grep "^//[^%]" $1 | sed 's,^//[[:space:]]*,,'
    echo
    grep -v "^//[^%]" $1 > patterns
    if [ "`tail -c 1 $1`" != "`echo`" ] ; then
        truncate -s-1 patterns
    fi
}

runflex()
{
    FLEX=`flex patterns 2>&1 | uniq`
    if [ "$FLEX" != "" ]
    then
        echo
        echo "flex reports:"
        echo "$FLEX"
        echo
        echo "(press Enter to continue)"
        read
    fi
}

runflexcpp()
{
    cat preamble patterns > lexer
    echo "Running ../tmp/bin/binary -K lexer > out"
    ../tmp/bin/binary -K lexer > out

    if [ -s out ] ; then
	echo "flexc++ (binary) reports:"
	echo "========================="
	echo
	cat out
	echo
	echo "========================="
	echo "To continue press Enter";
	read
    fi
}

makeprogram()
{
    echo compiling test $1
    g++ --std=c++14 -Wall main.cc lex.cc 
}

runprogram()
{
    echo 
    echo "Test $2: running the regression tests using input file \`$1':"
    echo "(compiling)..."
    echo

    makeprogram $2

    echo "Press Enter to start the regression test"
    read
    ./a.out $1 $nodebug

    echo "Press Enter to continue"
    read
}

if [ $# == 0 ]
then
    list=`ls p[[:digit:]]*`
else
    list="$*"
fi

for file in $list
do
    showinfo $file
    echo "Run $file [Yn]? "
    read YES
    if [ "$YES" != n ]
    then
        data=`echo $file | sed 's/p/i/'`
#        runflex 
        runflexcpp
        runprogram $data $file
    fi
done

rm -f a.out lex.cc lex.yy.c lexer main.o patterns scannerbase.h lexer.output out

